package com.bm.specialvehiclefordispatcher.activity.mysites;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.bm.corelibs.logic.BaseLogic.NListener;
import com.bm.corelibs.utils.ToastMgr;
import com.bm.specialvehiclefordispatcher.App;
import com.bm.specialvehiclefordispatcher.R;
import com.bm.specialvehiclefordispatcher.Tools.Tools;
import com.bm.specialvehiclefordispatcher.activity.BaseActivity;
import com.bm.specialvehiclefordispatcher.adapter.MySitesAdapter;
import com.bm.specialvehiclefordispatcher.bean.BaseData;
import com.bm.specialvehiclefordispatcher.bean.Station;
import com.bm.specialvehiclefordispatcher.constants.Constant;
import com.bm.specialvehiclefordispatcher.logics.LoginManager;
import com.bm.specialvehiclefordispatcher.logics.StationManager;
import com.bm.specialvehiclefordispatcher.views.CommonNavigationBar;

/**
 * @Copyright Copyright 2014 蓝色互动. All rights reserved.
 * 
 * @author GuoHao
 * @Date: 2015年8月25日 我的站点
 */
public class MySitesActivity extends BaseActivity implements android.view.View.OnClickListener, OnItemClickListener {

	CommonNavigationBar bar;
	EditText mysites_contacts;
	EditText mysites_keyword;
	LinearLayout mysites_search;
	ListView listView;
	Button sure_btn;
	MySitesAdapter adapter;
	List<Station> stations = new ArrayList<Station>();
	List<Station> tempList = new ArrayList<Station>();
	LinearLayout mysites_page1;
	LinearLayout mysites_page2;
	MapView mapView;
	BaiduMap baiduMap;
	TextView tv_sname, tv_name, tv_add;
	private BitmapDescriptor mCurrentMarker;
	/**
	 * 输入法
	 */
	private InputMethodManager imm;
	private StationManager manager = new StationManager();
	private Station myStation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mysites);
		findViews();
		init();
		addListeners();
	}

	@Override
	public void findViews() {
		bar = (CommonNavigationBar) findViewById(R.id.navi);
		mysites_contacts = (EditText) findViewById(R.id.mysites_contacts);
		mysites_keyword = (EditText) findViewById(R.id.mysites_keyword);
		mysites_search = (LinearLayout) findViewById(R.id.mysites_search);
		listView = (ListView) findViewById(R.id.mysites_listview);
		sure_btn = (Button) findViewById(R.id.mysites_sure);
		mysites_page1 = (LinearLayout) findViewById(R.id.mysites_page1);
		mysites_page2 = (LinearLayout) findViewById(R.id.mysites_page2);
		mapView = (MapView) findViewById(R.id.mysites_mapview);
		tv_sname = (TextView) findViewById(R.id.tv_sname);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_add = (TextView) findViewById(R.id.tv_add);
	}

	@Override
	public void init() {
		bar.setListener(null);
		bar.setTitle("我的站点");

		baiduMap = mapView.getMap();
		mapView.showZoomControls(false);
		imm = ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE));

		loadingDialog.show();
		manager.getMyStaion(LoginManager.getInstance(mActivity).getId(), myStationlListener());
	}
	
	private void setStationData(Station data) {
		tv_name.setText(data.dispatcherName + "( " + LoginManager.getInstance(mActivity).getPhone() + ")");
		tv_sname.setText(data.name);
		tv_add.setText(data.addAddress);
	}

	@Override
	public void addListeners() {
		sure_btn.setOnClickListener(this);
		mysites_search.setOnClickListener(this);
		listView.setOnItemClickListener(this);
		bar.showRightActionAndText("修改", new OnClickListener() {
			@Override
			public void onClick(View v) {
				loadingDialog.show();
				manager.getStationList("", alllListener());
			}
		});
		mysites_keyword.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.toString().length() == 0) {
					adapter = new MySitesAdapter(mActivity, stations);
					listView.setAdapter(adapter);
					tempList.clear();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

	}

	private NListener<BaseData> myStationlListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				if (data.status == Constant.STATUS_OK) {
					loadingDialog.dismiss();
					if (data.data != null && data.data.myStation != null) {
						mysites_page2.setVisibility(View.VISIBLE);
						mysites_page1.setVisibility(View.GONE);
						myStation = data.data.myStation;
						setStationData(myStation);
						intMap();
					}
				} else if(data.status == 2) {
					manager.getStationList("", alllListener());
				} else {
					loadingDialog.dismiss();
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}
	
	private NListener<BaseData> alllListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					if (data.data != null && data.data.stations != null) {
						stations = data.data.stations;
						mysites_page2.setVisibility(View.GONE);
						mysites_page1.setVisibility(View.VISIBLE);
						adapter = new MySitesAdapter(mActivity, stations);
						listView.setAdapter(adapter);
					}
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}
	
	private NListener<BaseData> setStationListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				if (data.status == Constant.STATUS_OK) {
					manager.getMyStaion(LoginManager.getInstance(mActivity).getId(), myStationlListener());
				} else {
					loadingDialog.dismiss();
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}

	public void moveToCentre(LatLng latLng) {
		MapStatus mMapStatus = new MapStatus.Builder().target(latLng).zoom(16).build();
		// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
		MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
		// 改变地图状态
		baiduMap.setMapStatus(mMapStatusUpdate);
	}

	public void intMap() {
		// baiduMap.setMyLocationEnabled(true);
		// // 构造定位数据
		// MyLocationData locData = new MyLocationData.Builder().accuracy(0)
		// // 此处设置开发者获取到的方向信息，顺时针0-360
		// .latitude(App.getInstance().getLatitude())
		// .longitude(App.getInstance().getLongitude()).build();
		// // 设置定位数据
		// baiduMap.setMyLocationData(locData);
		// // // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
		// // //
		// mCurrentMode = LocationMode.NORMAL; // 普通模式
		//
		// // baiduMap.setMyLocationEnabled(false);
		// baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
		// mCurrentMode, true, null));
		mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);

		System.out.println(App.getInstance().getLongitude() + "getLongitude");
		System.out.println(App.getInstance().getLatitude() + "getLatitude");

		OverlayOptions ooA = new MarkerOptions().position(new LatLng(myStation.latitude, myStation.longitude)).icon(mCurrentMarker).zIndex(5);
		baiduMap.addOverlay(ooA);
		moveToCentre(new LatLng(myStation.latitude, myStation.longitude));

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.mysites_search:
			tempList.clear();
			String str = mysites_keyword.getText().toString().trim();
			for (int i = 0; i < stations.size(); i++) {

				if (stations.get(i).name.indexOf(str) != -1) {
					tempList.add(stations.get(i));
					System.out.println(stations.get(i).name);
				}

			}
			adapter = new MySitesAdapter(mActivity, tempList);
			listView.setAdapter(adapter);

			break;
		case R.id.mysites_sure:
			boolean bl = false;
			long id = 0;
			//if (mysites_contacts.getText().toString().trim().length() > 0) {
				if (Tools.getTextViewText(mysites_keyword).length() == 0) {

					for (int i = 0; i < stations.size(); i++) {
						if (stations.get(i).isCheck == true) {
							id = stations.get(i).id;
							bl = true;
						}
					}

				} else {
					for (int i = 0; i < tempList.size(); i++) {
						if (tempList.get(i).isCheck == true) {
							id = stations.get(i).id;
							bl = true;
						}
					}
				}

				if (bl) {
					imm.hideSoftInputFromWindow(mysites_contacts.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(mysites_keyword.getWindowToken(), 0);
					loadingDialog.show();
					manager.setStation(id, LoginManager.getInstance(mActivity).getId(), setStationListener());
				} else {
					showToast("请选中一个站点以继续操作");
				}
			// } else {
			// showToast("请输入联系人");
			// }

			break;

		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		mapView.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
		mapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
		mapView.onPause();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (stations.size() > 0) {
			
			
			for (int i = 0; i < stations.size(); i++) {
				stations.get(i).isCheck = false;
			}
			stations.get(position).isCheck = true;
			
		}

		if (tempList.size() > 0) {
			
			if (stations.size()>0) {
				for (int i = 0; i < stations.size(); i++) {
					stations.get(i).isCheck = false;
				}
			}

			for (int i = 0; i < tempList.size(); i++) {
				tempList.get(i).isCheck = false;
			}
			tempList.get(position).isCheck = true;
		}
		
		

		adapter.notifyDataSetChanged();

	}

}
